jQuery(function($) {
	var cnt = 0;
	$('.f-form-widget-image input[type="file"], .f-form-widget-file input[type="file"]').live('change',function() {
		var file = $(this),
			target = '_fExtensionUploadTarget_' + (cnt++);
			parent = file.parent(),
			parentForm = file.parents('form:first'),
			form = $('<form method="POST" action="' + _fExtensionUploadUrl_ + 
				'" enctype="multipart/form-data" target="' + target + '">'),
			iframe = $('<iframe name="' + target + '" id="' + target + 
				'" style="display: none; ">');
		$('body').append(iframe).append(form);
		$('iframe#' + target).load(function() {
			var response = JSON.parse($(this).contents().find('body').text());
			if (response.error) {
				alert("Internal error");
			} else {
				var widget = file.parents('.f-form-widget:first');
				widget.find('input[type="hidden"]').val(response.id);
				widget.find('.f-upload-image-preview img').attr('src',response.temp_file);
				// TODO: thumbnail support
			}
			iframe.remove();
			parentForm.fForm('reEnable');
		});
		form.append(file);
		form.submit().get(0).reset();		
		parent.append(file);
		parentForm.fForm('disable');
		form.remove();
	});
});
